package com.mediacloud.app.newsmodule.activity

import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.media.MediaMetadata
import android.media.session.PlaybackState
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewStub
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.chinamcloud.audioserver.APSLifecycleKit
import com.chinamcloud.audioserver.MusicEntity
import com.chinamcloud.collect.AcquisitionManager
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager.Companion.getInstance
import com.lzf.easyfloat.interfaces.OnPermissionResult
import com.lzf.easyfloat.permission.PermissionUtils.checkPermission
import com.mediacloud.app.appfactory.cache.AppConfig
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.assembly.views.FontResizeView.OnFontChangeListener
import com.mediacloud.app.model.PaperFinishActivity
import com.mediacloud.app.model.eventbus.event.LoginEvent
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleItemReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.IntegralConfig
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.imagetext.ImageTextDetailFragment2
import com.mediacloud.app.newsmodule.model.AddHistoryParamsData
import com.mediacloud.app.newsmodule.pay.PaidMetas
import com.mediacloud.app.newsmodule.pay.PayContentResultRefreshListener
import com.mediacloud.app.newsmodule.utils.Addintegral
import com.mediacloud.app.newsmodule.utils.CollectionController
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager
import com.mediacloud.app.newsmodule.utils.DomainUtil
import com.mediacloud.app.newsmodule.utils.KillMusicUtils
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.newsmodule.utils.share.OnShareClickListener
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.newsmodule.view.FontResizeDialog
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.NewsDetailStyle
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle
import com.mediacloud.app.reslib.enums.TitileType
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.user.model.UserInfo
import com.tencent.mmkv.MMKV
import com.utils.NetUtils
import com.utils.UriTool.isFromH5OpenToReStart
import com.utils.read.AudioFloatManager.Companion.getInstance
import com.utils.read.AudioFloatManager.Companion.showPermissionAsk
import com.utils.read.ReadPlayView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import tv.danmaku.ijk.media.player.IMediaPlayer

/**
 * 新的图文文稿页面（简化流程重构版）
 * wy
 * */
class NormalNewsDetailActivity2 : StyleSetActivity() , PayContentResultRefreshListener,
    OnFontChangeListener{

    override fun getLayoutResID(): Int {
        return R.layout.activity_normal_news_detail
    }

    /**
     * 保存网页里面的全部图集
     */
    var manager: FragmentManager? = null
    var transaction: FragmentTransaction? = null
    var navigate_id: String? = null
    var article_id: String? = null
    var broccoliView: View? = null
    var isAutoPlay: Boolean? = null

    //语音播报
    var readNews: ImageView? = null
    var readPlayView: ReadPlayView? = null

    private var spiderAuthorLayout: View? = null
    private var spiderImage: ImageView? = null
    private var spiderAuthor: TextView? = null
    var spiderFollow: TextView? = null
    private var isSpider = false
    var isEpaper = false
    var fontShare: ShareWrap? = null
    var mTyReportStartTime: Long = 0
    var mTyReportEndTime: Long = 0


    private fun initViewStub() {
        val vs = findViewById<ViewStub>(R.id.vsBroccoli)
        vs.inflate()
        broccoliView = Utility.findViewById(mRootView, R.id.broccoli)
        if (!NetUtils.isNetConnection(this)) {
            rlayout_back.visibility = View.VISIBLE
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
            rlayout_back.setOnClickListener { finish() }
        }
    }


    protected var apsKit: APSLifecycleKit? = null

    //图文里处理起来很复杂 读稿、图文中插入了音频
    protected var activate = false



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun insertAudioPlay(event: StopReadNewsEvent?) {
        if (isFinishing || isDestroyed) {
            return
        }
        if (apsKit != null) {
            apsKit!!.unbindCallBacks()
        }
        activate = false
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun finishActivity(action: PaperFinishActivity?) {
        finish()
    }

    override fun finish() {
        super.finish()
        if (apsKit != null) {
            if (!apsKit!!.isPlaying()) {
                KillMusicUtils.hideReadNewsWin()
            }
            apsKit = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launchTimeLong = System.currentTimeMillis()
        loadingView = Utility.findViewById(mRootView, R.id.mLoadingView)
        rlayout_back = Utility.findViewById(mRootView, R.id.rlayout_back)
        mMoreText.visibility = View.GONE
        mTitlebar_MoreContainer.visibility = View.GONE
        spiderAuthorLayout = findViewById(R.id.spiderAuthorLayout)
        spiderImage = findViewById(R.id.spiderImage)
        spiderAuthor = findViewById(R.id.spiderAuthor)
        spiderFollow = findViewById(R.id.spiderFollow)
        spiderAuthor?.setTextColor(Color.parseColor(content_show_top_color))
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        val uriData = intent.data
        if (uriData != null) {
            isFromH5OpenToReStart = isFromH5OpenToReStart(this, uriData)
            val articleid = uriData.getQueryParameter("articleid")
            val title = uriData.getQueryParameter("title")
            val cname = uriData.getQueryParameter("cname")
            val tag = uriData.getQueryParameter("tag")
            catalogItem = CatalogItem()
            catalogItem.catname = cname
            articleItem = ArticleItem()
            try {
                articleItem?.title = (title)
                if (!TextUtils.isEmpty(articleid)) articleItem.id = (
                    java.lang.Long.valueOf(
                        articleid!!
                    )
                )
            } catch (e: Exception) {
            }
        } else {
            article_id = intent.getStringExtra("article_id")
            navigate_id = intent.getStringExtra("navigate_id")
            catalogItem = intent.getParcelableExtra("catalog")
            articleItem = intent.getParcelableExtra("data")
        }
        isAutoPlay = intent.getBooleanExtra("isAutoPlay", false)
        if (catalogItem == null) catalogItem = CatalogItem()
        catalogItem.catalog_type = intent.getStringExtra("category")
        if (!TextUtils.isEmpty(navigate_id)) {
            catalogItem.catid = navigate_id
        }
        if (articleItem == null) {
            articleItem = ArticleItem()
            articleItem.id = (java.lang.Long.valueOf("" + article_id))
            articleItem.summary = intent.getStringExtra("summary")
            articleItem.title = (intent.getStringExtra("title"))
            articleItem.url = (intent.getStringExtra("url"))
            articleItem.isAdvertisement = intent.getIntExtra("isAdvertisement", 0)
            articleItem.isBarrage = intent.getIntExtra("isBarrage", 0)
            articleItem.referSourceID = intent.getStringExtra("ReferSourceID")
            articleItem.isComment = intent.getStringExtra("isComment")
        }

        isPreview = articleItem.preview
        isEpaper = intent.getBooleanExtra("IS_EPAPER", false)
        initViewChildren()
        onPageStart()
        getNewsData()
        fontShare!!.articleItem = articleItem
        shareWrap.articleItem = articleItem
        setNewsTitle()
        showPageTransition()
        DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES)
        //设置服务器自定义图标
        setCustomIcom()
        getInstance(this).openArticleId = articleItem.getId()
        val string = MMKV.defaultMMKV().getString(XKey.CACHE_HOME_TAB_ID, "")
    }


    protected fun setNewsTitle() {
        val base = serverAppConfigInfo.getBase()
        if (base == TitileType.FRAME) {
            setFrameTypeTitle()
        } else if (base == TitileType.NAVIGATE) {
            setTitle(if (catalogItem != null) catalogItem.catname else "")
        } else if (base == TitileType.NEWS_TITLE) {
            mTitlebar_name.visibility = View.INVISIBLE
            setTitle(if (articleItem != null) articleItem.getTitle() else "")
        } else if (base == TitileType.NOTITLE) {
            setTitle("")
        }
    }

    override fun needLoadTopSecondBgSkin(): Boolean {
        return super.subClassgetNeedTopSecondBgSkin()
    }

    override fun getNewsDetailNavigateBarStyle(): NavigateBarStyle? {
        return AppFactoryGlobalConfig.getAppServerConfigInfo(this).imgtxtNewsBar
    }

    override fun getStatusBarColor(): Int {
        return if (imageTextDetailFragment != null && imageTextDetailFragment!!.isFullScreen) Color.TRANSPARENT else super.getStatusBarColor()
    }

    var isFullScreen = false



    var imageTextDetailFragment: ImageTextDetailFragment2? = null


    protected fun getNewsData() {
        val old = imageTextDetailFragment
        imageTextDetailFragment = ImageTextDetailFragment2()

        val bundle = Bundle()
        bundle.putParcelable("data", articleItem)
        bundle.putParcelable("catalog", catalogItem)
        imageTextDetailFragment!!.arguments = bundle
        try {
            manager = supportFragmentManager
            transaction = manager!!.beginTransaction()
            transaction!!.replace(R.id.detailContentContainer, imageTextDetailFragment!!)
            if (old != null) {
                transaction!!.remove(old)
            }
            transaction!!.commitAllowingStateLoss()
        } catch (e: Exception) {
        }
//        if (articleItem != null) {
//            getNewsDetail();
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTouch(event: MotionEvent?): Boolean {
        if (isFullScreen) return false
        if ("0" == articleItem.isComment) {
            showCommentRelativeView(false)
        }
        hideInputComment()
        return false
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun ontoggleFullScreen(isFullScreen: Boolean) {
        this.isFullScreen = isFullScreen
        if (isFullScreen) {
            if (NewsDetailStyle.TopMenu == serverAppConfigInfo.content_show) {
                mTitileBar.visibility = View.GONE
                hideInputComment()
            }
            bottomBarLayout.visibility = View.GONE


        } else {
            bottomBarLayout.visibility = View.VISIBLE
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(loginEvent: LoginEvent?) {
        if (isFinishing || isDestroyed) {
            return
        }
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin) {
            getNewsData()
        }
    }

    private fun addHistory() {
        val paramsData = AddHistoryParamsData()
        paramsData.source = CollectionController.convertToSource(catalogItem)
        if (articleItem.getId() > 0) {
            paramsData.source_id = articleItem.getId()
        } else {
            if (!TextUtils.isEmpty(articleItem.referTarget)) {
                try {
                    paramsData.source_id = articleItem.referTarget.toLong()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        paramsData.summary = articleItem.summary
        paramsData.title = articleItem.getTitle()
        paramsData.type = articleItem.getType().toString() + ""
        paramsData.url = articleItem.getUrl()
        paramsData.logo = articleItem.logo
        paramsData.publishdate_format = articleItem.publishdate_format
    }

    var flag = true

    // @Subscribe(threadMode = ThreadMode.MAIN)
    fun success(data: ArticleItemReciver) {
        if (isFinishing || isDestroyed) {
            return
        }
        if (data.state && data.articleItem != null /*&&(articleItem!=null&&articleItem.getId()==data.articleItem.getId())*/) {
            articleItem = data.articleItem
            if (articleItem.isComment == "0") {
                isComment = articleItem.isComment
                orderView()
            }
            sendExposureEvent()
            fontShare!!.articleItem = articleItem //bottem Share
            shareWrap.articleItem = articleItem //titleMore Share
            if (articleItem.fromComponent != 1) setNewsTitle()
            if (!flag) {
                return
            }
            flag = false
            /* readNews.postDelayed(new Runnable() {
                @Override
                public void run() {
                    addHistory();
                }
            },1000);*/if (imageTextDetailFragment != null) {
                imageTextDetailFragment!!.setUpdateTheData(articleItem)
            }
            refreshBottomStyle(articleItem, 1)
            data.articleItem.isEPaper = isEpaper
            fontShare!!.init(data.articleItem, catalogItem, object : OnShareClickListener {
                override fun onSharePraiseClick() {}
                override fun onShareCommentClick() {}
                override fun onShareCollectionClick() {}
                override fun onTextFontClick() {
                    val fontResizeDialog = FontResizeDialog(
                        this@NormalNewsDetailActivity2,
                        this@NormalNewsDetailActivity2
                    )
                    fontResizeDialog.show()
                }
            })
            if (articleItem.spider != null) {
                spiderImage!!.load(articleItem.spider.userImage)
                spiderAuthor!!.text = articleItem.spider.userName
                spiderFollow!!.setOnClickListener {
                    if (isFastClick()) {
                        imageTextDetailFragment!!.changeAttentionStatus()
                    }
                }
                isSpider = true
            }
            //判断是否是军报
            if (articleItem.isEPaper) {
                judgeInteval()
            }
        } else {
            fault(null)
        }
    }

    var config: IntegralConfig? = null
    var openInteval = false //是否开启积分任务

    var timeInteval = 0 //增加积分时间（分）

    var time = 0 //累计时长


    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                if (time <= timeInteval) {
                    time++
                    sendEmptyMessageDelayed(0, 1000)
                } else {
                    Addintegral.addintegral(this@NormalNewsDetailActivity2, 48, articleItem)
                    time = 0
                    sendEmptyMessageDelayed(0, 1000)
                }
            }
        }
    }

    //判断是否开启积分和无和成长任务
    private fun judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig
        if (config != null) {
            if (config!!.enableList1 != null && config!!.enableList1.size != 0) {
                for (i in config!!.enableList1.indices) {
                    if (config!!.enableList1[i] == 48) {
                        openInteval = true
                        timeInteval = config!!.paper_least_duration_1
                    }
                }
            }
        }
        time = MMKV.defaultMMKV().getInt("ImageText2_Time" + UserInfo.getUserInfo(this).userid, 0)
        if (time >= timeInteval) { //判断有没有累计时间
            time = 0
        }
        if (openInteval && time < timeInteval) {
            handler.sendEmptyMessageDelayed(0, 1000)
        }
    }

    fun fault(data: Any?) {
        if (isFinishing || isDestroyed) {
            return
        }
        if (data == null) {
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
        } else {
            showStateView(TYPE_NO_CONTENT, false)
        }
    }

    protected fun initViewChildren() {
        initStateView()
        loadingView.setOnClickListener {
            if (NetUtils.isNetConnection(this@NormalNewsDetailActivity2)) {
                if (TYPE_LOADING != currentState) {
                    showStateView(TYPE_LOADING, false)
                    getNewsData()
                }
            }
        }
        mTitlebar_name = findViewById(R.id.mTitlebar_name)
    }

    override fun closeStateView() {
        super.closeStateView()
        rlayout_back.visibility = View.GONE
        if (broccoliView != null) {
            broccoliView!!.postDelayed(Runnable {
                if (isFinishing || isDestroyed) {
                    return@Runnable
                }
                val animation = ObjectAnimator.ofFloat(broccoliView, "alpha", 0f)
                animation.startDelay = 10
                animation.addListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {}
                    override fun onAnimationEnd(animation: Animator) {
                        broccoliView!!.visibility = View.GONE
                    }

                    override fun onAnimationCancel(animation: Animator) {}
                    override fun onAnimationRepeat(animation: Animator) {}
                })
                animation.start()
            }, 10)
        }
    }

    override fun toggleTitleBar(open: Boolean) {
        super.toggleTitleBar(open)
        fontShare = ShareWrap(this, false)
        fontShare!!.setShowFunction(true)
        if (open) {
            textSizeCtl.setImageResource(R.drawable.imagetext_more)
            textSizeCtl.visibility = View.VISIBLE
            textSizeCtl.setOnClickListener(View.OnClickListener { v ->
                if (!TextUtils.isEmpty(isPreview) && isPreview == "1") {
                    ToastUtil.show(this@NormalNewsDetailActivity2, "预览稿件不支持当前操作")
                    return@OnClickListener
                }
                fontShare!!.show(v)
            })
        } else {
            textSizeCtl.visibility = View.GONE
        }
    }

    override fun openTitleBarSetting(): Boolean {
        return true
    }


    protected fun hideInputComment() {
        if (isShowComment(articleItem)) {
            showCommentRelativeView(true)
        } else {
            showCommentRelativeView(false)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (requestCode == MemberActivity.REQUEST_CODE && intent != null && intent.getBooleanExtra(
                MemberActivity.REQUEST_KEY,
                false
            )
        ) {

        }
    }


    override fun onBackPressed() {
        var value = imageTextDetailFragment != null && imageTextDetailFragment!!.onBackPressed()
        if (shareWrap.isShowing()) {
            shareWrap.dismiss()
            value = true
        }
        if (value) return
        super.onBackPressed()
    }

    var launchTimeLong: Long = 0
    override fun onDestroy() {
        super.onDestroy()
        CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(System.currentTimeMillis()-inTime)/1000)

        handler.removeCallbacksAndMessages(null)
        if (time > 0) {
            MMKV.defaultMMKV().putInt("ImageText2_Time" + UserInfo.getUserInfo(this).userid, time)
        }
        KillMusicUtils.stopAPS(this)
        if (imageTextDetailFragment != null) {
            imageTextDetailFragment!!.clearWebView()
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        if (articleItem != null) {
            if (imageTextDetailFragment != null) {
                try {
                    manager = supportFragmentManager
                    transaction = manager!!.beginTransaction()
                    transaction!!.remove(imageTextDetailFragment!!)
                    transaction!!.commitAllowingStateLoss()
                } catch (e: Exception) {
                }
            }
        }
        manager = null
        transaction = null
    }

    protected fun intoLogin(context: Context?) {
        //   ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source = "稿件详情"
        LoginUtils.invokeLogin(context)
    }





    /**
     * 是否是会员
     */
    fun isMember(): Boolean {
        return false
    }

    override fun onStart() {
        super.onStart()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readEnter(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }

    override fun onStop() {
        super.onStop()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readExit(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }

    override fun refreshNewPayResultContent(paidMetas: PaidMetas) {
        imageTextDetailFragment!!.updateBuyContent(paidMetas)
        imageTextDetailFragment!!.showHTMLData(paidMetas.content)
        imageTextDetailFragment!!.initReadNews()
    }


    var lastLevel = -1

    override fun onFontChange(levelIndex: Int) {
        if (levelIndex == lastLevel) {
            return
        }
        lastLevel = levelIndex
        if (imageTextDetailFragment != null) {
            val zoom = AppConfig.zoomSize[levelIndex]!!
            imageTextDetailFragment!!.resizeFont(levelIndex, zoom)
        }
    }

}